import asyncio
import logging

from aiohttp import web


async def index(req: web.Request):
    logging.info('Request: {}, match_info: {}', req.url, req.match_info)
    return web.Response(body='<h1>Hello AIOHttp</h1>')


async def hello(req: web.Request):
    logging.info('Request: {}, match_info: {}', req.url, req.match_info)
    return web.Response(body=f'<h1>Hello {req.match_info["name"]}</h1>')


async def create_server_deprecated(loop):  # 新版的web_runner已经对loop进行了一次封装
    app = web.Application(loop=loop)
    app.router.add_route('GET', '/', index)
    app.router.add_route('GET', '/{name}', hello)
    return await loop.create_server(app, host='localhost', port=24680)


def test1():  # web_runner中进行了一次封装，这种方式已废弃
    loop = asyncio.get_event_loop()
    loop.run_until_complete(create_server_deprecated(loop))
    print('server start.')
    loop.run_forever()


async def create_server():  # 内部默认采用了asyncio.get_event_loop()作为事件循环处理器
    app = web.Application()
    app.add_routes([web.get('/', index), web.get('/{name}', hello)])
    runner = web.AppRunner(app)
    await runner.setup()
    print(runner.server, runner.addresses, runner.sites)


def test2():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(loop.create_task(create_server()))
    print('server start.')
    loop.run_forever()


def test3():
    app = web.Application()
    app.add_routes([web.get('/', index), web.get('/{name}', hello)])  # Django风格
    web.run_app(app, host='localhost', port=24680, reuse_address=True)


if __name__ == '__main__':
    """
        asyncio可以实现单线程并发IO操作,可以作为请求客户端类似于requests，也可以用在服务器端可以用单线程+coroutine实现多用户的高并发支持
        asyncio实现了TCP、UDP、SSL等协议，aiohttp则是基于asyncio实现的HTTP框架。
    """
    # test1()   # 不行，不是这样用的, 3.4前教程
    # test2()   # 不行，不是这样用的
    test3()
